<?php
namespace app\common\controller;

use alipay\AlipayTradeService;
use alipay\builder\AlipayTradePrecreateContentBuilder;
use think\Controller;
use think\Db;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Session;
use wxpay\WeiXinNativePay;
use wxpay\WxPayUnifiedOrder;

class HomeBase extends CommonBase
{
    protected $user_info = null;

    protected function initialize()
    {
        parent::initialize();

        $user_info = Session::get('user_info');
        if (!empty($user_info))
        {
            $this->user_info = model('user')->where(['id' => $user_info['id']])->find();
        }

        $this->assign('index_style',"");
        $this->assign('user_info',$this->user_info);
    }

    /**
     * 站点SEO
     * @param string $seo_type 页面类型
     * @param array $param 参数
     * @throws
     */
    protected function site_seo($seo_type = "",$param = array())
    {
        $seo_config = Config::pull("seo");

        $site_title = $seo_config['site_title'];
        $keywords = $seo_config['site_keywords'];
        $description = $seo_config['site_description'];

        if ($seo_type == "classify") { // 分类
            if(!empty($seo_config['site_classify_title'])){
                $site_title = trim(str_replace(array('{site_name}','{category_name}'), array($this->siteConfig['site_title'],$param['category_name']), $seo_config['site_classify_title']));
            }
            if(!empty($seo_config['site_classify_keywords'])){
                $keywords = trim(str_replace(array('{site_name}','{category_name}'), array($this->siteConfig['site_title'],$param['category_name']), $seo_config['site_classify_keywords']));
            }
            if(!empty($seo_config['site_classify_description'])){
                $description = trim(str_replace(array('{site_name}','{category_name}'), array($this->siteConfig['site_title'],$param['category_name']), $seo_config['site_classify_description']));
            }

        } else if ($seo_type == 'article'){ //详情

            if(!empty($seo_config['site_details_title'])){
                $site_title = trim(str_replace(array('{site_name}','{title}','{category_name}'), array($this->siteConfig['site_title'],$param['title'],$param['category_name']), $seo_config['site_details_title']));
            }
            if(!empty($seo_config['site_details_keywords'])){
                $keywords = trim(str_replace(array('{site_name}','{title}','{category_name}'), array($this->siteConfig['site_title'],$param['title'],$param['category_name']), $seo_config['site_details_keywords']));
            }
            if(!empty($seo_config['site_details_description'])){
                $description = trim(str_replace(array('{site_name}','{title}','{category_name}'), array($this->siteConfig['site_title'],$param['title'],$param['category_name']), $seo_config['site_details_description']));
            }
        }else if ($seo_type == 'search'){ //搜索

            if(!empty($seo_config['site_search_title'])){
                $site_title = trim(str_replace(array('{site_name}','{word}'), array($this->siteConfig['site_title'],$param['word']), $seo_config['site_search_title']));
            }
            if(!empty($seo_config['site_search_keywords'])){
                $keywords = trim(str_replace(array('{site_name}','{word}'), array($this->siteConfig['site_title'],$param['word']), $seo_config['site_search_keywords']));
            }
            if(!empty($seo_config['site_search_description'])){
                $description = trim(str_replace(array('{site_name}','{word}'), array($this->siteConfig['site_title'],$param['word']), $seo_config['site_search_description']));
            }
        } else { //默认

            if(!empty($seo_config['site_title'])){
                $site_title = trim(str_replace(array('{site_name}'), array($this->siteConfig['site_title']), $seo_config['site_title']));
            }
            if(!empty($seo_config['site_keywords'])){
                $keywords = trim(str_replace(array('{site_name}'), array($this->siteConfig['site_title']), $seo_config['site_keywords']));
            }
            if(!empty($seo_config['site_description'])){
                $description = trim(str_replace(array('{site_name}'), array($this->siteConfig['site_title']), $seo_config['site_description']));
            }
        }

        $site_seo = array(
            'title' =>  $site_title,
            'keywords' =>   $keywords,
            'description' =>   $description,
        );

        $this->assign('site_seo', $site_seo);
    }

    /**
     * 创建订单
     * @param string $payType //支付类型
     * @param string $title //商品标题
     * @param $amount //金额
     * @param int $userId // 用户id
     * @param int $productId // 产品id
     * @return array
     * @throws \wxpay\WxPayException
     */
    protected function createOrder($payType = '',$title = '',$amount,$userId = 0,$productId = 0)
    {
        // 生成订单编号
        $outTradeNo = date('Ymdhis').mt_rand(100,10000);
        $qrUrl = '';

        if ($payType == "alipay")
        {
            $qrUrl = $this->createAlipay($title,$amount,$outTradeNo);
        }else {
            $qrUrl = $this->createWxPay($title,$amount,$outTradeNo,$productId);
        }

        return [
            'qrcode' => $qrUrl,
            'trade_no' => $outTradeNo,
            'user_id' => $userId,
        ];
    }

    /**
     * 创建微信支付
     * @param $title //标题
     * @param $totalAmount //金额
     * @param $outTradeNo //订单号
     * @param $productId  //产品id
     * @throws \wxpay\WxPayException
     */
    private function createWxPay ($title,$totalAmount,$outTradeNo,$productId)
    {
        $totalAmount = $totalAmount * 100;

        $input = new WxPayUnifiedOrder();
        $input->SetBody($title);
        $input->SetOut_trade_no($outTradeNo);
        $input->SetTotal_fee($totalAmount);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id($productId);

        $notify = new WeiXinNativePay();
        $result = $notify->GetPayUrl($input);
        if ($result['result_code'] == "SUCCESS" && $result['return_code'] == "SUCCESS")
        {
            return $result['code_url'];
        }
        return false;
    }


    /**
     * 支付宝支付
     * @param $title //商品标题
     * @param $totalAmount //订单金额
     * @param $outTradeNo //订单号
     * @return false
     */
    private function createAlipay($title,$totalAmount,$outTradeNo)
    {
        // 创建请求builder，设置请求参数
        $qrPayRequestBuilder = new AlipayTradePrecreateContentBuilder();
        $qrPayRequestBuilder->setOutTradeNo($outTradeNo);
        $qrPayRequestBuilder->setTotalAmount($totalAmount);
        $qrPayRequestBuilder->setSubject($title);

        // 调用qrPay方法获取当面付应答
        $qrPay = new AlipayTradeService();
        $qrPayResult = $qrPay->qrPay($qrPayRequestBuilder);

        if ($qrPayResult->getTradeStatus() == "SUCCESS")
        {
            $response = $qrPayResult->getResponse();
            if ($response->code == 10000) {
                return $response->qr_code;
            }
        }
        return false;
    }

    protected function checkLogin () {
        if ($this->request->action() != "callback" && $this->request->action() != "login")
        {
            $user = Session::get('user_info');
            if (empty($user)) {
                $this->error("请先登录后再操作!",url('/login',array(),'html',true));
            }
        }
    }

}